package com.jeady.timetodo.manager

import android.content.Context
import android.content.Intent
import android.hardware.biometrics.BiometricManager.Authenticators
import android.hardware.biometrics.BiometricPrompt
import android.os.CancellationSignal
import android.provider.Settings
import android.util.Log
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat.startActivity
import com.jeady.timetodo.base.showToast
import java.util.concurrent.Executor

private val TAG = "[Authentication]"
object Authentication {
    fun finger(context: Context, mainExecutor: Executor, callback: (verified: Boolean) -> Unit) {
        val biometricManager = BiometricManager.from(context)
        when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)) {
            BiometricManager.BIOMETRIC_SUCCESS -> {
                Log.d("MY_APP_TAG", "App can authenticate using biometrics.")
                val bio = BiometricPrompt.Builder(context)
                    .setTitle("证明你有绝对控制权")
//                    .setSubtitle("证明你是App的管理者")
                    .setAllowedAuthenticators(Authenticators.BIOMETRIC_STRONG or Authenticators.DEVICE_CREDENTIAL)
//                    .setNegativeButton("取消验证", mainExecutor) { _, _ ->
//                        Log.e(TAG, "onCreate: click negative buttton")
//                        showToast(context, "验证取消")
//                        callback(false)
//                    }
                    .build()
                bio.authenticate(
                    CancellationSignal(), mainExecutor,
                    object : BiometricPrompt.AuthenticationCallback() {
                        override fun onAuthenticationFailed() {
                            super.onAuthenticationFailed()
                            Log.d(TAG, "onAuthenticationFailed: ")
                            callback(false)
                        }

                        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) {
                            super.onAuthenticationSucceeded(result)
                            Log.d(TAG, "onAuthenticationSucceeded: ")
                            callback(true)
                        }
                        override fun onAuthenticationError(
                            errorCode: Int,
                            errString: CharSequence?
                        ) {
                            super.onAuthenticationError(errorCode, errString)
                            Log.d(TAG, "onAuthenticationError: ")
                            callback(false)
                        }
                    }
                )
            }
            BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
                Log.e("MY_APP_TAG", "No biometric features available on this device.")
                callback(false)
            }
            BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->{
                Log.e("MY_APP_TAG", "BIOMETRIC_ERROR_HW_UNAVAILABLE.")
                callback(false)
            }
            BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
                showToast(context, "尚未启用")
                val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
                    putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                        BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
                }
                startActivity(context, enrollIntent, null)
            }
        }
    }
    @Composable
    fun PinManager(modifier: Modifier=Modifier, confirmText: String="验证", callback: (pinInput: String) -> Unit){
        val context = LocalContext.current
        LazyVerticalGrid(GridCells.Fixed(6),
            modifier.background(MaterialTheme.colorScheme.background),
            contentPadding = PaddingValues(10.dp),
            horizontalArrangement = Arrangement.spacedBy(10.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ){
            var pinInput by mutableStateOf("")
            item(span={ GridItemSpan(2) }){
                Button({
                    callback("")
                }) {
                    Text("取消")
                }
            }
            item(span={ GridItemSpan(2) }){}
            item(span={ GridItemSpan(2) }){
                Button({
                    pinInput = ""
                }) {
                    Text("清空")
                }
            }
            item(span = {
                GridItemSpan(6)
            }) {
                TextField(pinInput, {
                        pinInput = it
                    },
                    singleLine = true,
                    textStyle = TextStyle(textAlign = TextAlign.Center)
                )
            }
            val codes = mutableListOf<Char>()
            for(c in 'A'..'Z') codes.add(c)
            for(c in '0'..'9') codes.add(c)
            for(code in codes){
                item {
                    val interactionSource = remember{ MutableInteractionSource() }
                    val pressedInteraction by interactionSource.collectIsHoveredAsState()
                    val shape = remember{ CutCornerShape(10.dp) }
                    Box(
                        Modifier
                            .aspectRatio(1f)
                            .background(
                                if (pressedInteraction) Color(0xff5acc8c) else
                                    if(pinInput.contains(code)) Color(0xff2aac5c)
                                    else Color(0xff1abc9c),
                                shape
                            )
                            .clip(shape)
                            .clickable(
                                interactionSource, rememberRipple(
                                    color = Color.Black
                                )
                            ) {
                                pinInput += code
                            },
                        contentAlignment = Alignment.Center
                    ){
                        Text("$code")
                    }
                }
            }
            item(span = { GridItemSpan(6) }) {
                Button({
                    if(pinInput.isEmpty()){
                        showToast(context, "不能为空")
                    }else {
                        callback(pinInput)
                    }
                }) {
                    Text(confirmText)
                }
            }
        }
    }

    @Composable
    fun GestureManager(modifier: Modifier=Modifier, callback: (verified: Boolean) -> Unit){

    }
}